package Controller;

import DAO.UserDao;
import entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "userController", value = "/userController")
public class userController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String purpose = request.getParameter("purpose");
        String username = request.getParameter("username");

        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        System.out.println("Purpose:"+purpose+"\n username:"+username);

        UserDao userDao = new UserDao();

        if (purpose.equals("ranking")) { // 排名
            List<User> userList = userDao.queryByScoreSort();
            request.getSession().setAttribute("userlist",userList);
            request.getRequestDispatcher("topScore.jsp").forward(request,response);
        } else if (purpose.equals("change")) {

            String name = request.getParameter("name");
            String password = request.getParameter("password");
            String email = request.getParameter("email");

            int score = userDao.queryByUsername(username).getScore();
            System.out.println(score);

            userDao.deleteByUsername(username);
            userDao.queryRegister(username,name,password,email,score);
            User user = userDao.queryByUsername(username);

            request.getSession().setAttribute("user",user);
            request.getRequestDispatcher("usercenter.jsp").forward(request,response);

        } else if (purpose.equals("userinfo")) {
            User user = userDao.queryByUsername(username);
            request.getSession().setAttribute("user",user);
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
